<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>websocket</title>
</head>
<body>


<div id="responseText"></div>

<div>
    <input id="messageInput" type="text" >

    <button type="button" onclick="send();">发送</button>
</div>

</body>

<script type="application/javascript">
    var socket;


    if (!window.WebSocket) {

        window.WebSocket = window.MozWebSocket;
    }

    if (window.WebSocket) {
        socket = new WebSocket("ws://localhost:8081/websocket");

        socket.onmessage = function (event) {

            var ta = document.getElementById('responseText');
            ta.innerHTML += "<br>" + event.data + "\r\n";
        };

        socket.onopen = function (event) {

            var ta = document.getElementById('responseText');
            ta.innerHTML = "打开WebSoket 服务正常，浏览器支持WebSoket!" + "\r\n";

        };

        socket.onclose = function (event) {

            var ta = document.getElementById('responseText');
            ta.innerHTML = "";
            ta.innerHTML = "WebSocket 关闭" + "\r\n";
        };
    } else {
        alert("您的浏览器不支持WebSocket协议！");
    }

    function send() {
        var mi = document.getElementById('messageInput');
        var message = mi.value;
        if (!window.WebSocket) {
            return;
        }
        if (socket.readyState == WebSocket.OPEN) {
            socket.send(message);
        } else {
            alert("WebSocket 连接没有建立成功！");
        }

    }
</script>
</html>